package controllers;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import models.GantiPassword;
import models.Profil;
import models.User;
import system.Controller;
import system.MailServer;

/**
 * Kelola User
 * 
 * @author Rezan Achmad
 */
@WebServlet(name = "UserController", urlPatterns = {"/user", "/user/", "/user/index", "/user/update", "/user/resetPassword"})
public class UserController extends Controller {

    @Override
    protected void initRules() {
        // Admin
        rules.put("/user", identity.isAdmin());
        rules.put("/user/", identity.isAdmin());
        rules.put("/user/index", identity.isAdmin());
        
        // Non Guest
        rules.put("/user/update", !identity.isGuest());
    }
    
    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String userPath = request.getServletPath();

        if (userPath.equals("/user") || userPath.equals("/user/") || userPath.equals("/user/index")) {
            actionIndex(request, response);
        } else if (userPath.equals("/user/update")) {
            actionUpdate(request, response);
        } else if (userPath.equals("/user/resetPassword")) {
            actionResetPassword(request, response);
        } else {
            // Other
        }
    }

    private void actionIndex(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Find and set list user
        request.setAttribute("users", User.getInstance().getAll());
        
        // Set View
        setView("/user/index", request, response);
    }

    private void actionUpdate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get user id
        int userId = Integer.parseInt(request.getParameter("id"));
        
        // Get user
        User user = User.getInstance().get(userId);
        
        // Create GantiPassword model
        GantiPassword gantiPassword = new GantiPassword(user);
        
        if(isPost) {
            // Update role
            if(request.getParameter("update_type").equals("role")) {
                user.role_id = Integer.parseInt(request.getParameter("role_id"));
                user.update(false);
            }
            
            // Update Info
            if(request.getParameter("update_type").equals("info")) {
                user.nama_lengkap = request.getParameter("nama_lengkap");
                user.nama_panggilan = request.getParameter("nama_panggilan");
                user.email = request.getParameter("email");
                user.alamat = request.getParameter("alamat");
                user.no_telepon = request.getParameter("no_telepon");
                user.update();
            }
            
            // Update password
            if(request.getParameter("update_type").equals("password")) {
                // Set atribut
                gantiPassword.password_lama = request.getParameter("password_lama");
                gantiPassword.password_baru = request.getParameter("password_baru");
                gantiPassword.re_password_baru = request.getParameter("re_password_baru");
                
                // Ganti password
                if(gantiPassword.execute()) {
                    // Berhasil
                    gantiPassword = new GantiPassword(user);
                    gantiPassword.message = "Password berhasil diganti";
                }
            }
        }
        
        // Set user model
        request.setAttribute("user", user);
        
        // Set ganti password model
        request.setAttribute("gantiPassword", gantiPassword);
        
        // Set View
        setView("/user/update", request, response);
    }
    
    private void actionResetPassword(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get user id
        int userId = Integer.parseInt(request.getParameter("id"));
        
        // Find user
        User user = User.getInstance().get(userId);
        
        // Reset Password
        String newPassword = user.resetPassword();
        String message = "";
        
        if(newPassword != null) {
            sendEmailResetPassword(user, newPassword);
            message = "Reset password berhasil";
        } else {
            message = "Reset password gagal";
        }
        
        // Set mesage
        request.setAttribute("message", message);
        
        // Set View
        setView("/user/resetPassword", request, response);
    }
    
    protected void sendEmailResetPassword(User user, String newPassword) {
        String to[] = new String[]{user.email};
        String subject = "Reset Password";
        String message = "Dear " + user.nama_lengkap + ",\n\nYour password has been reset.\nYour new password is " + newPassword;
        
        MailServer.sendEmail(to, subject, message);
    }
}
